package com.eric.service.impl;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eric.domain.bso.UserPermissionBso;
import com.eric.domain.dto.UserPermissionDto;
import com.eric.domain.po.SysPermission;
import com.eric.domain.po.UserPermission;
import com.eric.mapper.UserPermissionMapper;
import com.eric.service.ISysPermissionService;
import com.eric.service.IUserPermissionService;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static com.eric.utils.Constant.PAGE_CURRENT;
import static com.eric.utils.Constant.PAGE_SIZE;

/**
 * <p>
 * 用户权限表 服务实现类
 * </p>
 *
 * @author 新哥
 * @since 2024-03-12
 */
@Service
@RequiredArgsConstructor
@Transactional
public class UserPermissionServiceImpl extends MPJBaseServiceImpl<UserPermissionMapper, UserPermission> implements IUserPermissionService {
    private final ISysPermissionService permissionService;


    @Override
    @Transactional
    public SaResult saveUserPermission(Map<String, List<Integer>> paramMaps) {

//        获取到前端传进的user_id,PermissionIdList
        List<Integer> userIds_Vue = paramMaps.get("userIds");
        List<Integer> permissionIds_Vue = paramMaps.get("permissionIds");
//        获取数据库中Permission的全部permission
        List<SysPermission> permissionList_db = permissionService.list();
//        把获取到的Permission的permissionId放到一个列表permissionIdList中
        List<Integer>permissionIdList_db=new ArrayList<>();
        for (SysPermission sysPermission : permissionList_db) {
            permissionIdList_db.add(sysPermission.getId());
        }
//        判断传进来的数据permissionIds是否都包含在数据库中，是通过，否就return错误
        boolean b = new HashSet<>(permissionIdList_db).containsAll(permissionIds_Vue);
        if (!b){
            return SaResult.error("输入的权限数据库中不存在，请检查后再次输入！");
        }
//      只使用0索引，因为都只是一个userId
        Integer userIdVue = userIds_Vue.get(0);
//      通过前端传来的user_id查询数据库，获取UserPermission对象列表--mybatis-plus的list()方法
        List<UserPermission> userPermissionInDb = query().eq("user_id", userIdVue).list();
//      如果数据库中一条数据都没有 ，就添加进去
        if (userPermissionInDb.isEmpty()){
            List<UserPermission>userPermissionList=new ArrayList<>();
            for (Integer permissionId : permissionIds_Vue) {
                UserPermission userPermission=new UserPermission();
                userPermission.setUserId(userIdVue);
                userPermission.setPermissionId(permissionId);
                userPermissionList.add(userPermission);
            }

            saveBatch(userPermissionList);
            return SaResult.ok("新UserPermission数据已经被添加！");
        }

//        把数据库中查询到的UsePermission对象转换成UserPermissionBso类型列表（只有user_id,permission_id两个属性）
        List<UserPermissionBso> userPermissionBsosInDb = BeanUtil.copyToList(userPermissionInDb, UserPermissionBso.class);
//        把前端传进来的数据，生成userPermissionBso类型
        List<UserPermissionBso>userPermissionBsoListVue=new ArrayList<>();
        for (Integer permissionId : permissionIds_Vue) {
            UserPermissionBso userPermissionBso=new UserPermissionBso();
            userPermissionBso.setUserId(userIdVue);
            userPermissionBso.setPermissionId(permissionId);
            userPermissionBsoListVue.add(userPermissionBso);
        }
        userPermissionBsoListVue.removeAll(userPermissionBsosInDb);
        List<UserPermission> userPermissionList = BeanUtil.copyToList(userPermissionBsoListVue, UserPermission.class);
        if (userPermissionList.isEmpty()){
            return SaResult.error("UserPermission数据已存在，请检查后再次输入!");
        }
//            通过登录id和userService，获取到用户的realName
//        String realName = userService.getById(Integer.parseInt(StpUtil.getLoginId().toString())).getRealName();
//        userPermissionList.forEach(userPermission -> {
//            userPermission.setCreateBy(realName);
//            userPermission.setLastUpdateBy(realName);
//        });


        saveBatch(userPermissionList);
        return SaResult.ok("新的UserPermission数据已经被添加！");
    }
    @Override
//    获取登录用户的权限列表
//    如果在user_permission表中没有注册user_permission关系，默认返回一个sys:visit权限
    public List<String> getLoginUserPermissionList(Object loginId, String s) {
        int login_Id = Integer.parseInt(loginId.toString());
//        根据userId查询UserPermission表数据，返回UserPermission对象列表
        List<UserPermission> userPermissionList = query().eq("user_id", login_Id).list();
//        把查到的对象列表转换成UserPermissionBso对象列表
        List<UserPermissionBso> userPermissionBsoList = BeanUtil.copyToList(userPermissionList, UserPermissionBso.class);
//        获取到PermissionId列表
        List<Integer>userPermission_PermissionIds=new ArrayList<>();
        for (UserPermissionBso userPermissionBso : userPermissionBsoList) {
            userPermission_PermissionIds.add(userPermissionBso.getPermissionId());
        }
//     todo   如果userPermission_PermissionIds集合为空，返回一个权限sys:visit回到SaToken
        if (userPermission_PermissionIds.isEmpty()){
            List<String>permissionIdList=new ArrayList<>();
            permissionIdList.add("sys:visit");
            return permissionIdList;
        }
//        如果不为空，执行下面代码
//        根据获取到的PermissionId列表，查询SysPermission表的数据，用MybatisPlus的listByIds方法
        List<SysPermission> permissionList = permissionService.listByIds(userPermission_PermissionIds);
//        把获取到的SysPermission对象中获取到的PermissionName放到一个String类型列表中
        List<String>permissionNameList=new ArrayList<>();
        for (SysPermission sysPermission : permissionList) {
            permissionNameList.add(sysPermission.getPermissionName());
        }
//       把这个列表返回
        return permissionNameList;
    }

    /*
     *     作用：删除指定User对应的Permission权限
     *     参数是一个Map，2个键值对
     *     第一个键值对：userIds:[userId]
     *     第二个键值对: permissionIds:[permissionId]
     *     现在把userIds的数组元素写死是一个，permissionId数组可以1~N个
     *     如果在user_permission表中没有注册user_permission关系，默认返回一个sys:visit权限
     *     user-permission表，就用一个增加，一个删除就够了，毕竟这个表很少用
     * */
    @Override
    @Transactional
    public SaResult deleteUserPermissionsService(Map<String, List<Integer>> ids) {
        //        从Map中获取userId和permissionId的List<Integer>
        List<Integer> userIds = ids.get("userIds");
        List<Integer> permissionIds = ids.get("permissionIds");

//        分别判断userId和permissionIds是否为空
        if (userIds.isEmpty()){
            return SaResult.error("userId缺失，请重新输入！");
        }
        if (permissionIds.isEmpty()){
            return SaResult.error("permissionId缺失，请重新输入！");
        }
//        降低程序的复杂度，前端仅仅传输一个userId
        Integer userId = userIds.get(0);
        List<UserPermissionDto>userPermissionDtoList=new ArrayList<>();
        for (Integer permissionId : permissionIds) {
            UserPermissionDto userPermissionDto=new UserPermissionDto();
            userPermissionDto.setUserId(userId);
            userPermissionDto.setPermissionId(permissionId);
            userPermissionDtoList.add(userPermissionDto);
        }
        List<UserPermission> userPermissionList = BeanUtil.copyToList(userPermissionDtoList, UserPermission.class);
        for (UserPermission userPermission : userPermissionList) {
            MPJLambdaWrapper<UserPermission>wrapper=new MPJLambdaWrapper<UserPermission>()
                    .eq(UserPermission::getUserId,userId)
                    .eq(UserPermission::getPermissionId,userPermission.getPermissionId());
            remove(wrapper);
        }
        return SaResult.ok();
    }

    @Override
    public SaResult getAllService(Integer current, Integer pageSize) {
        if (current==null){
            current=PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<UserPermission>page=new Page<>(current,pageSize);
        List<UserPermission> userPermissionList = query().orderByDesc("update_time").page(page).getRecords();
        List<UserPermissionDto> userPermissionDtoList = BeanUtil.copyToList(userPermissionList, UserPermissionDto.class);
        return SaResult.data(userPermissionDtoList);
    }

    @Override
    public SaResult getByUserIdService(Integer userId) {
        if (userId==null){
            return SaResult.error("userId不能为空");
        }
        List<UserPermission> userPermissionList = query().eq("user_id", userId).list();

        List<UserPermissionDto> userPermissionDtoList = BeanUtil.copyToList(userPermissionList, UserPermissionDto.class);

        return SaResult.data(userPermissionDtoList);
    }

    @Override
    public SaResult getByIdService(Integer id) {
        if (id==null){
            return SaResult.error("id参数不能为空");
        }
        UserPermission userPermission = query().eq("id", id).one();
        UserPermissionDto userPermissionDto = BeanUtil.copyProperties(userPermission, UserPermissionDto.class);
        return SaResult.data(userPermissionDto);
    }

    @Override
    public SaResult getByPermissionIdService(Integer permissionId, Integer current, Integer pageSize) {
        if (permissionId==null){
            return SaResult.error("userId不能为空");
        }
        if (current==null){
            current=1;
        }
        if (pageSize==null){
            pageSize=10;
        }
        Page<UserPermission>page=new Page<>(current,pageSize);
        List<UserPermission> userPermissionList = query()
                .eq("permission_id", permissionId)
                .orderByDesc("update_time")
                .page(page).getRecords();
        List<UserPermissionDto> userPermissionDtoList = BeanUtil.copyToList(userPermissionList, UserPermissionDto.class);
        return SaResult.data(userPermissionDtoList);
    }

    @Override
    @Transactional

    public SaResult updateUserPermission(Map<String, List<Integer>> paramMaps) {

        //        获取前端传来的user_id,permissionIdList
        List<Integer> userIds_Vue = paramMaps.get("userIds");
        List<Integer> permissionIds_Vue = paramMaps.get("permissionIds");


//        获取数据库中permission的全部permission
        List<SysPermission> permissionList_db = permissionService.list();
//        把获取到的permission的permissionId放到一个列表permissionIdList中
        List<Integer> permissionIdList_db = new ArrayList<>();
        for (SysPermission sysPermission : permissionList_db) {
            permissionIdList_db.add(sysPermission.getId());
        }

//        判断传进来的数据permissionIds是否都包含在数据库中，是通过，否就return错误
        boolean b = new HashSet<>(permissionIdList_db).containsAll(permissionIds_Vue);

        if (!b) {
            return SaResult.error("输入的权限数据库中不存在，请检查后再次输入！");
        }
        //      只使用0索引，因为都只是一个userId
        Integer userIdVue = userIds_Vue.get(0);
        //      通过前端传来的user_id查询数据库，获取UserPermission对象列表--mybatis-plus的list()方法
        List<UserPermission> userPermissionInDb = query().eq("user_id", userIdVue).list();

        List<Integer> ids = new ArrayList<>();
        for (UserPermission userPermission : userPermissionInDb) {
            ids.add(userPermission.getId());
        }
//        第一步：先删除原来的UserPermission对象
        removeByIds(ids);
//        第二步：再添加新的UserPermission对象
        List<UserPermission> userPermissionList = new ArrayList<>();
        for (Integer permissionId : permissionIds_Vue) {
            UserPermission userPermission = new UserPermission();
            userPermission.setUserId(userIdVue);
            userPermission.setPermissionId(permissionId);
            userPermissionList.add(userPermission);
        }
        boolean saveBatch = saveBatch(userPermissionList);
        return saveBatch ? SaResult.ok("UserPermission数据更新成功！") : SaResult.error("UserPermission数据更新失败！");

    }
}






























